package com.example.demo.controller;

import com.example.demo.Repository.BookRepository;
import com.example.demo.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

    @RestController
    @RequestMapping("/api/books")
    @CrossOrigin(origins = "http://localhost:5500") // 允许前端跨域访问
    public class BookController {

        @Autowired
        private BookRepository bookRepository;

        // 获取所有图书
        @GetMapping
        public List<Book> getAllBooks() {
            return bookRepository.findAll();
        }

        // 添加图书
        @PostMapping
        public Book addBook(@RequestBody Book book) {
            return bookRepository.save(book);
        }

        // 删除图书
        @DeleteMapping("/{id}")
        public void deleteBook(@PathVariable Long id) {
            bookRepository.deleteById(id);
        }
    }

